/**
 * Copyright [2019] [LiBo/Alex of copyright liboware@gmail.com ]
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.hyts.expression.ognl.handler;

import com.google.common.base.Preconditions;
import com.hyts.expression.ognl.handler.base.AbstractValueHandler;
import com.hyts.guava.String.Strings;
import ognl.Ognl;
import ognl.OgnlContext;
import ognl.OgnlException;

import java.util.Objects;

/**
 * @project-name:coffice-toolbox
 * @package-name:com.hyts.expression.ognl.handler
 * @author:LiBo/Alex
 * @create-date:2019-08-06 10:07
 * @copyright:libo-alex4java
 * @email:liboware@gmail.com
 * @description:
 */
public class BeanValueHandler extends AbstractValueHandler {

    /**
     * 构造器服务功能
     * @param ognlContext
     */
    public BeanValueHandler(OgnlContext ognlContext) {
        super(ognlContext);
    }

    /**
     * 获取getBean对象名称的属性properties对应的值
     * @param beanName
     * @param properties
     *
     * 内置多级别的对象之间的调用 需要 ben.properties1.properties2
     * 内置多级别的实例方法之间的调用 需要 bean.properties.method(param);
     * 内置多级别的静态方法之间的调用 需要 fullPathClasspath.method(param);
     *
     * @return
     */
    public Object getBeanValue(String beanName, String properties){
        Preconditions.checkArgument(Strings.isNotBlank(beanName),"传入的属性对象key不可以为空!");
        Preconditions.checkArgument(Strings.isNotBlank(properties),"传入的属性对象properties不可以为空!");
        try {
            return Ognl.getValue(Ognl.parseExpression(String.format("#%s.%s",beanName,properties)),ognlContext,ognlContext.getRoot());
        } catch (OgnlException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     *  获取getBean对象名称的属性properties对应的值
     *  内置多级别的对象之间的调用 需要 ben.properties1.properties2
     *  内置多级别的实例方法之间的调用 需要 bean.properties.method();
     *  内置多级别的静态方法之间的调用 需要 fullPathClasspath.method(param);
     * @param properties
     * @return
     */
    public Object getRootValue(String properties){
        Preconditions.checkArgument(Strings.isNotBlank(properties),"传入的属性对象properties不可以为空!");
        try {
            return Ognl.getValue(Ognl.parseExpression(properties),ognlContext,ognlContext.getRoot());
        } catch (OgnlException e) {
            e.printStackTrace();
            return null;
        }
    }


}
